package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.UserHomeDetailPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_UserUserActFulWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_UserUserActFulWindow().init(
                4004,
                2,
                "Dws_UserUserActFul",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //TODO 过滤首页和详情页记录
        SingleOutputStreamOperator<JSONObject> filterHomeAndDetail = etl(stream);
        //TODO 转成POJO
        SingleOutputStreamOperator<UserHomeDetailPageViewBean> beanStream = parseToPojo(filterHomeAndDetail);
        //TODO 开窗聚合
        SingleOutputStreamOperator<UserHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
        //TODO 将结果写入到 clickhouse中
        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<UserHomeDetailPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_page_view_window", UserHomeDetailPageViewBean.class));
    }

    private SingleOutputStreamOperator<UserHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<UserHomeDetailPageViewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserHomeDetailPageViewBean>() {
                                    @Override
                                    public long extractTimestamp(UserHomeDetailPageViewBean obj, long recordTimestamp) {
                                        return obj.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserHomeDetailPageViewBean>() {
                            @Override
                            public UserHomeDetailPageViewBean reduce(UserHomeDetailPageViewBean bean1, UserHomeDetailPageViewBean bean2) throws Exception {
                                bean1.setHomeUvCt(bean1.getHomeUvCt() + bean2.getHomeUvCt());
                                bean1.setCourseDetailUvCt(bean1.getCourseDetailUvCt() + bean2.getCourseDetailUvCt());
                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<UserHomeDetailPageViewBean, UserHomeDetailPageViewBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx, Iterable<UserHomeDetailPageViewBean> elements, Collector<UserHomeDetailPageViewBean> out) throws Exception {
                                UserHomeDetailPageViewBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<UserHomeDetailPageViewBean> parseToPojo(SingleOutputStreamOperator<JSONObject> filterHomeAndDetail) {
        return filterHomeAndDetail
                .keyBy(new KeySelector<JSONObject, String>() {
                    @Override
                    public String getKey(JSONObject obj) throws Exception {
                        return obj.getJSONObject("common").getString("mid");
                    }
                })
                .process(new KeyedProcessFunction<String, JSONObject, UserHomeDetailPageViewBean>() {
                    private ValueState<String> homeState;
                    private ValueState<String> courseDetailState;
                    @Override
                    public void open(Configuration parameters) throws Exception {

                        homeState = getRuntimeContext().getState(new ValueStateDescriptor<String>("homeState", String.class));
                        courseDetailState = getRuntimeContext().getState(new ValueStateDescriptor<String>("courseDetailState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<UserHomeDetailPageViewBean> out) throws Exception {
                        Long ts = value.getLong("ts");
                        String pageId = value.getJSONObject("page").getString("page_id");

                        String today = AtguiguUtil.toDate(ts);

                        long homeUvCt = 0L;
                        String homeDate = homeState.value();
                        if ("home".equals(pageId) && !today.equals(homeDate)) {
                            homeUvCt = 1L;
                            homeState.update(today);
                        }

                        long courseDetailUvCt = 0L;
                        String courseDetailDate = courseDetailState.value();
                        if ("course_detail".equals(pageId) && !today.equals(courseDetailDate)) {
                            courseDetailUvCt = 1L;
                            courseDetailState.update(today);
                        }

                        UserHomeDetailPageViewBean bean = new UserHomeDetailPageViewBean("", "", homeUvCt, courseDetailUvCt, ts);
                        if (homeUvCt + courseDetailUvCt == 1) {
                            out.collect(bean);
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject obj) throws Exception {
                        String pageId = obj.getJSONObject("page").getString("page_id");
                        return "home".equals(pageId) || "course_detail".equals(pageId);
                    }
                });
    }
}
